package cn.felord.app.security;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.util.Assert;

/**
 * The type Jwt entity builder.
 *
 * @author Dax
 * @since 14 :16  2019-04-10
 */
public class JwtPairBuilder {
    private int accessTokenExpDays;
    private int refreshTokenExpDays;


    /**
     * Instantiates a new Jwt entity builder.
     *
     * @param accessTokenExpDays  the access token exp days
     * @param refreshTokenExpDays the refresh token exp days
     */
    public JwtPairBuilder(int accessTokenExpDays, int refreshTokenExpDays) {
        Assert.isTrue(accessTokenExpDays > 0, "accessToken must more than 0");
        Assert.isTrue(refreshTokenExpDays > accessTokenExpDays, "accessToken must less than refreshToken");
        this.accessTokenExpDays = accessTokenExpDays;
        this.refreshTokenExpDays = refreshTokenExpDays;
    }

    /**
     * New jwt entity jwt entity.
     *
     * @param jwtClaims         the jwt claims
     * @param jwtTokenGenerator the jwt token generator
     * @param jwtTokenStorage   the jwt token storage
     * @return the jwt entity
     * @throws JsonProcessingException the json processing exception
     */
    public JwtPair newJwtPair(JwtClaims jwtClaims, JwtTokenGenerator jwtTokenGenerator, JwtTokenStorage jwtTokenStorage) throws JsonProcessingException {
        JwtClaimsBuilder jwtClaimsBuilder = new JwtClaimsBuilder();

        JwtClaims claims = jwtClaimsBuilder
                .iss(jwtClaims.getIss())
                .sub(jwtClaims.getSub())
                .uid(jwtClaims.getAud())
                .uname(jwtClaims.getUname())
                .roles(jwtClaims.getRoles())
                .expDays(accessTokenExpDays)
                .builder();
        JwtClaims refreshJwtClaims = jwtClaimsBuilder
                .iss(jwtClaims.getIss())
                .sub(jwtClaims.getSub())
                .uid(jwtClaims.getAud())
                .uname(jwtClaims.getUname())
                .roles(jwtClaims.getRoles())
                .expDays(refreshTokenExpDays)
                .builder();

        String accessToken = jwtTokenGenerator.jwtToken(claims);
        String refreshToken = jwtTokenGenerator.jwtToken(refreshJwtClaims);
        JwtPair jwtPair = new JwtPair();
        jwtPair.setAccessToken(accessToken);
        jwtPair.setRefreshToken(refreshToken);
//            存入缓存
        jwtTokenStorage.put(jwtPair, jwtClaims.getAud());
        return jwtPair;
    }

}
